<template>
  <div>
    <el-card>
      <div class="common-layout">
        <el-container>
          <el-header style="font-size: large; padding: 20px">基本信息</el-header>
          <el-container>
            <el-main>
              <el-form ref="formRef" label-position="right" :rules="rules" :model="order" label-width="200px">
                <el-row :gutter="30">
                  <el-col :span="8">
                    <el-form-item label="订单编号" prop="orderCode" size="large">
                      <el-input v-model="order.orderCode" size="large" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="供应商名称" prop="supplierName" size="large">
                      <el-input v-model="order.supplierName" size="large" disabled placeholder="请选择供应商名称">
                        <template #suffix>
                          <el-icon style="cursor: pointer" @click="handleShowSupplierDialog">
                            <Search />
                          </el-icon>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="供应商编码" prop="supplierCode" size="large">
                      <el-input v-model="order.supplierCode" size="large" placeholder="请选择供应商编号" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="30">
                  <el-col :span="8">
                    <el-form-item label="订单状态" prop="state" size="large">
                      <el-input v-model="order.state" size="large" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item prop="totalPriceWithoutTax" size="large" style="text-align: right">
                      <template #label>
                        <el-tooltip
                          content="订单金额（不含税）= SUM(订单明细金额（不含税）* 要求的数量)"
                          placement="bottom"
                          effect="dark"
                        >
                          <el-icon style="color: lightgreen"><WarningFilled /></el-icon>
                        </el-tooltip>
                        订单金额（不含税）
                      </template>
                      <el-input v-model="order.totalPriceWithoutTax" size="large" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="订单金额（含税）" prop="totalPriceWithTax" size="large">
                      <template #label>
                        <el-tooltip
                          content="订单金额（含税）= SUM(订单明细金额（含税）* 要求的数量)"
                          placement="bottom"
                          effect="dark"
                        >
                          <el-icon style="color: lightgreen"><WarningFilled /></el-icon>
                        </el-tooltip>
                        订单金额（含税）
                      </template>
                      <el-input v-model="order.totalPriceWithTax" size="large" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="30">
                  <el-col :span="8">
                    <el-form-item label="币种" prop="orderCurrency" size="large">
                      <el-select v-model="order.orderCurrency" placeholder="请选择币种">
                        <el-option v-for="item in Currency" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="采购组织" prop="purchaseOrg" size="large">
                      <el-select v-model="order.purchaseOrg" placeholder="请选择采购组织">
                        <el-option v-for="item in Org" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="采购组" prop="purchaseGroup" size="large">
                      <el-select v-model="order.purchaseGroup" clearable placeholder="请选择采购组">
                        <el-option v-for="item in Group" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="30">
                  <el-col :span="8">
                    <el-form-item label="订单类型" prop="orderType" size="large">
                      <el-select v-model="order.orderType" clearable placeholder="请选择订单类型">
                        <el-option v-for="item in sort" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="采购企业编码" prop="purchaseId" size="large">
                      <el-input v-model="order.purchaseId" size="large" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="采购企业名称" prop="purchaseName" size="large">
                      <el-input v-model="order.purchaseName" size="large" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="30">
                  <el-col :span="8">
                    <el-form-item label="需要确认" prop="needConfirm" size="large">
                      <el-input v-model="order.needConfirm" size="large" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="需要提供ASN" prop="publishAsn" size="large">
                      <el-input v-model="order.publishAsn" size="large" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="订单创建日期" prop="createTime" size="large">
                      <el-input v-model="order.createTime" size="large" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="30">
                  <el-col :span="8">
                    <el-form-item label="订单标识" prop="orderIdentification" size="large">
                      <el-input v-model="order.orderIdentification" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col>
                    <el-form-item label="订单备注" prop="orderNotes" size="large">
                      <el-input
                        v-model="order.orderNotes"
                        clearable
                        placeholder="请输入备注"
                        type="textarea"
                        maxlength="100"
                        show-word-limit
                        @input="descInput"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-form-item label="上传附件" prop="batchID" size="large" width="20px">
                  <el-upload
                    class="upload-demo"
                    drag
                    action="http://192.168.100.179:9097/admin/order/flieUpload/166666"
                    multiple
                  >
                    <el-icon class="el-icon--upload"><Plus /></el-icon>
                    <template #tip>
                      <div class="el-upload__tip">每个文件最大4M,仅支持PDF,excel,word,jpg,png格式文件</div>
                    </template>
                  </el-upload>
                </el-form-item>
                <el-form-item>
                  <el-col>
                    <el-button type="primary" style="float: center" @click="submitForm">提交</el-button>
                  </el-col>
                </el-form-item>
              </el-form>
            </el-main>
          </el-container>
        </el-container>
      </div>
    </el-card>
    <el-card>
      <el-container>
        <el-header style="font-size: large; padding: 20px">订单明细</el-header>
        <div class="mb-4">
          <el-button type="success" size="large" @click="onAddItem">添加物料信息</el-button>
          <el-button size="large" @click="deleteRows">批量删除</el-button>
        </div>
        <el-table :data="materialForm" style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="maktx_zh" label="物料名称" width="180" align="center" />
          <el-table-column prop="material_code" label="物料编码" width="180" align="center">
            <template #default="{ $index }">
              <el-input v-model="materialForm[$index].material_code" placeholder="请输入物料编码">
                <template #append>
                  <el-icon @click="handleShowMaterialDialog($index)">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="material_spec" label="物料规格" width="180" align="center" />
          <el-table-column prop="meins" label="基本计量单位" width="180" align="center" />
          <el-table-column prop="batch_id" label="图纸" width="180" align="center" />
          <el-table-column prop="packaging_id" label="包装规格" width="180" align="center" />
          <el-table-column prop="contract_code" label="合同编号" width="180" align="center">
            <template #default="{ $index }">
              <el-input v-model="materialForm[$index].contract_code" placeholder="请输入合同编号">
                <template #suffix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column prop="number" label="要求的数量" width="180" align="center">
            <template #default="{ $index }">
              <el-input-number
                v-model="materialForm[$index].number"
                placeholder="请输入数量"
                contrls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column prop="deliver_date" label="要求的交货日期" width="200" align="center">
            <template #default="{ $index }">
              <el-date-picker v-model="materialForm[$index].deliver_date" type="date" placeholder="请选择交货日期" />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="要求的单价（不含税）" width="180" align="center" />
          <el-table-column prop="tax_included_or_not" label="是否含税" width="180" align="center" />
          <el-table-column prop="tax_rate" label="税率" width="180" align="center" />
          <el-table-column prop="requested_price_with_tax" label="要求的单价（含税）" width="180" align="center" />
          <el-table-column prop="factory" label="采购方工厂" width="180" align="center" />
          <el-table-column prop="unloading_point" label="卸货点" width="180" align="center" />
          <el-table-column prop="operate" fixed="right" label="操作" width="180" align="center">
            <template #default="scope">
              <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.$id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-container>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog v-model="showSupplierDialog" title="供应商信息">
      <el-table
        border
        :data="supplier"
        table-layout="auto"
        style="width: 100%"
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column prop="supplierCode" label="供应商编码" />

        <el-table-column prop="supplierName" label="供应商名称" />
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSupplierDialog = false">取 消</el-button>
          <el-button type="primary" @click="confirmSelection">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 弹窗2.0 -->
    <el-dialog title="导入数据" v-model="showImportDialog">
      <el-upload
        class="upload-demo"
        action="http://192.168.100.179:9097/admin/order/flieUpload/166666"
        :on-success="handleSuccess"
        :before-upload="beforeUpload"
        ref="uploadRef"
      >
        <el-button @click="importData">选择文件</el-button>
        <div v-if="fileName">上传文件名：{{ fileName }}</div>
        <template #tip>
          <div class="el-upload__tip">每个文件最大4M,仅支持PDF,excel,word,jpg,png格式文件</div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button type="primary" @click="importData">确认导入</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 弹窗3.0 -->
    <el-dialog v-model="showMaterialDialog.isShow" title="物料信息" width="800px">
      <el-table
        border
        :data="material"
        table-layout="auto"
        style="width: 100%"
        highlight-current-row
        @row-click="handleRowClicks"
      >
        <el-table-column prop="maktx_zh" label="物料名称" width="200" />
        <el-table-column prop="material_code" label="物料编码" width="200" />
        <el-table-column prop="material_spec" label="物料规格" width="200" />
        <el-table-column prop="meins" label="基本计量单位" width="200" />
        <el-table-column prop="batch_id" label="图纸" width="200" />
        <el-table-column prop="packaging_id" label="包装规格" width="200" />
        <el-table-column prop="contract_code" label="合同编号" width="200" />
        <el-table-column prop="number" label="要求的数量" width="200" />
        <el-table-column prop="deliver_date" label="要求的交货日期" width="200" />
        <el-table-column prop="price" label="要求的单价（不含税）" width="200" />
        <el-table-column prop="tax_included_or_not" label="是否含税" width="200" />
        <el-table-column prop="tax_rate" label="税率" width="200" />
        <el-table-column prop="requested_price_with_tax" label="要求的单价（含税）" width="200" />
        <el-table-column prop="factory" label="采购方工厂" width="200" />
        <el-table-column prop="unloading_point" label="卸货点" width="200" />
      </el-table>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMaterialDialog.isShow = false">取 消</el-button>
          <el-button type="primary" @click="confirmSelections">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { Plus, Search, WarningFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElIcon, ElMessageBox, ElNotification } from 'element-plus'

// 下拉菜单选项
const Currency = ref([
  { value: 'CNY', label: '人民币' },
  { value: 'USD', label: '美元' }
])
const Org = ref([
  { value: 'A', label: 'A组织' },
  { value: 'B', label: 'B组织' }
])
const Group = ref([
  { value: 'G1', label: '第一组' },
  { value: 'G2', label: '第二组' }
])
const sort = ref([
  { value: 'p', label: 'P订单类型' },
  { value: 'U', label: 'U订单类型' }
])

const formRef = ref()
const rules = {
  supplierName: [{ required: true, message: '供应商名称不能为空', trigger: 'blur' }],
  supplierCode: [{ required: true, message: '供应商编码不能为空', trigger: 'blur' }],
  orderCurrency: [{ required: true, message: '币种不能为空', trigger: 'change' }],
  orderType: [{ required: true, message: '订单类型不能为空', trigger: 'change' }]
}

const submitForm = async () => {
  await formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('表单提交成功')
    } else {
      ElMessage.error('表单校验失败')
    }
  })
  try {
    const response = await axios.post('http://192.168.100.179:9097/admin/order/add', order)
    console.log(response.data)
  } catch (error) {
    console.error('Error submitting form:', error)
  }
}

const descInput = (value: string) => {
  console.log(`当前输入了${value.length}个字`)
}

const total = ref(0)
const Current = ref(1)
const size = ref(10)

//搜索物料编码
const material = ref([])
const materialForm = ref([
  {
    maktx_zh: '',
    material_code: '',
    material_spec: '',
    meins: '',
    batch_id: '',
    packaging_id: '',
    contract_code: '',
    number: '',
    deliver_date: '',
    price: '',
    tax_included_or_not: '',
    tax_rate: '',
    requested_price_with_tax: '',
    factory: '',
    unloading_point: ''
  }
])
const showMaterialDialog = ref({
  isShow: false,
  index: 0,
  materialObj: {} as any
})
const handleShowMaterialDialog = (i: number) => {
  showMaterialDialog.value.isShow = true
  showMaterialDialog.value.index = i
  fetchData()
}
const confirmSelections = () => {
  materialForm.value[showMaterialDialog.value.index] = showMaterialDialog.value.materialObj
  console.log(materialForm.value[showMaterialDialog.value.index], showMaterialDialog.value.index, '99999')

  showMaterialDialog.value.isShow = false
}

//获取订单明细
const fetchData = async () => {
  try {
    // const {
    //   data: { data }
    // }
    const response = await axios({
      method: 'get',
      url: 'http://192.168.100.138:9097/admin/orderItems/all',
      data: {
        currentPage: Current.value,
        pageSize: size.value
      }
    })
    console.log(response.data)

    material.value = response.data.map((item: any) => {
      return {
        maktx_zh: item.maktx_zh,
        material_code: item.material_code,
        material_spec: item.material_spec,
        meins: item.meins,
        batch_id: item.batch_id,
        packaging_id: item.packaging_id,
        contract_code: item.contract_code,
        number: item.number,
        deliver_date: item.deliver_date,
        price: item.price,
        tax_included_or_not: item.tax_included_or_not,
        tax_rate: item.tax_rate,
        requested_price_with_tax: item.requested_price_with_tax,
        factory: item.factory,
        unloading_point: item.unloading_point
      }
    })
    console.log(material.value)
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}
onMounted(() => {
  fetchDate()
})
const handleSizeChange = (newSize) => {
  size.value = newSize
  Current.value = 1 // 重置当前页码为1
  fetchDate()
}
const handleCurrentChange = (newPage) => {
  Current.value = newPage
  fetchDate()
}
const handleRowClicks = (row) => {
  // const list = {
  //   maktx_zh: row.maktx_zh,
  //   material_code: row.material_code,
  //   material_spec: row.material_spec,
  //   meins: row.meins,
  //   batch_id: row.batch_id,
  //   packaging_id: row.packagingId,
  //   contract_code: row.contract_code,
  //   number: row.number,
  //   deliver_date: row.deliver_date,
  //   price: row.price,
  //   tax_included_or_not: row.tax_included_or_not,
  //   tax_rate: row.tax_rate,
  //   requested_price_with_tax: row.requested_price_with_tax,
  //   factory: row.factory,
  //   unloading_point: row.unloading_point
  // }
  // materialForm.value[Current.value - 1] = list
  showMaterialDialog.value.materialObj = row
  console.log(showMaterialDialog.value.materialObj)
}

const isAddDialogVisible = ref(false)

//前端删除
const now = new Date()

const deleteRow = (index: number) => {
  materialForm.value.splice(index, 1)
}
const deleteRows = (indices: number[]) => {
  for (let i = indices.length - 1; i >= 0; i--) {
    materialForm.value.splice(indices[i], 1)
  }
}

//新增
const onAddItem = () => {
  now.setDate(now.getDate() + 1)
  materialForm.value.push({
    maktx_zh: '',
    material_code: '',
    material_spec: '',
    meins: '',
    batch_id: '',
    packaging_id: '',
    contract_code: '',
    number: '',
    deliver_date: '',
    price: '',
    tax_included_or_not: '',
    tax_rate: '',
    requested_price_with_tax: '',
    factory: '',
    unloading_point: ''
  })
}

//弹窗
const supplier = ref([])
const order = reactive({
  orderCode: '',
  supplierName: '',
  supplierCode: '',
  state: '',
  totalPriceWithoutTax: '',
  totalPriceWithTax: '',
  orderCurrency: '',
  purchaseOrg: '',
  purchaseGroup: '',
  orderType: '',
  purchaseId: '',
  purchaseName: '',
  needConfirm: '',
  publishAsn: '',
  createTime: '',
  orderIdentification: '',
  orderNotes: '',
  batchId: ''
})
const showSupplierDialog = ref(false)
const handleShowSupplierDialog = () => {
  showSupplierDialog.value = true
  fetchDate()
  console.log(supplier.value)
}
const confirmSelection = () => {
  console.log('确认选择供应商')

  showSupplierDialog.value = false
}
//供应商
const fetchDate = async () => {
  try {
    const response = await axios({
      method: 'post',
      url: 'http://192.168.100.179:9097/admin/supplier/querySupplierPage',
      data: {}
    })
    const result = response.data
    supplier.value = result.data.records.map((items) => {
      return {
        supplierName: items.supplierName,
        supplierCode: items.erpCode
      }
    })
    total.value = result.data.total
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}
const handleRowClick = (row) => {
  const list = {
    supplierName: row.supplierName,
    supplierCode: row.supplierCode
  }
  Object.assign(order, list)
}

//上传
const imageUrl = ref('')
const showImportDialog = ref(false)
const uploadRef = ref<HTMLInputElement | null>(null)
const beforeUpload = (file: File) => {
  const maxFileSize = 4 * 1024 * 1024
  // 获取文件的扩展名
  const extension = file.name.slice(((file.name.lastIndexOf('.') - 1) >>> 0) + 2)

  // 检查文件扩展名是否为 .xls 或 .xlsx
  const isXLS = extension.toLowerCase() === 'xls'
  const isXLSX = extension.toLowerCase() === 'xlsx'
  const isPDF = extension.toLowerCase() === 'pdf'
  const isDOCX = extension.toLowerCase() === 'docx'
  const isDOC = extension.toLowerCase() === 'doc'
  const isJPG = extension.toLowerCase() === 'jpg'
  const isPNG = extension.toLowerCase() === 'png'
  // 检查文件大小是否超出限制
  if (file.size > maxFileSize) {
    ElMessage.error('文件大小不能超过 4M!')
    return false
  }
  if (!isXLS && !isXLSX && !isPDF && !isDOCX && !isDOC && !isJPG && !isPNG) {
    ElMessage.error('仅支持PDF,excel,word,jpg,png格式文件!')
    return false
  }
  return true
}
const fileName = ref('')
const handleSuccess = (response: any, file: File, fileList: any) => {
  fileName.value = file.name
  ElMessage.success('文件上传成功')
  showImportDialog.value = false // 关闭对话框
}

const importData = () => {
  if (uploadRef.value) {
    ;(uploadRef.value as HTMLInputElement).click() // 触发点击上传
  } else {
    ElMessage.error('上传组件未初始化')
  }
}
</script>

<style>
.el-card {
  margin: 20px 10px;
}

.el-scrollbar__view {
  width: 100%;
}
/* 
.el-table__body {
  width: 100% !important;
} */
.el-form-item__label {
  align-items: center;
}
.el-upload {
  --el-upload-dragger-padding-horizontal: 5px;
  --el-upload-dragger-padding-vertical: 0;
}
</style>
